package com.z.common.config.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Component
//public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler {
public class MyAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {
    @Resource
    private ObjectMapper objectMapper;

    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        if("json".equals("json")){
            httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
            httpServletResponse.setHeader("Access-Control-Allow-Methods", "*");
            httpServletResponse.setContentType("application/json;charset=UTF-8");
            httpServletResponse.setStatus(HttpStatus.UNAUTHORIZED.value());
            Map<String, Object> map = new HashMap<>();
            if(e instanceof LockedException){
                map.put("message", "账户已被锁定");
            }else if(e instanceof BadCredentialsException){
                map.put("message", "账户或密码错误");
            }else if(e instanceof DisabledException){
                map.put("message", "账户已被禁用");
            }else {
                map.put("message", "登录失败");
            }
            httpServletResponse.getWriter().write(objectMapper.writeValueAsString(map));
        }else {
            super.onAuthenticationFailure(httpServletRequest, httpServletResponse, e);
        }
    }
}